'use strict';
const axios = require('axios');
const db = uniCloud.database();
const chatCollection = db.collection('chats');

// Deepseek API配置
const DEEPSEEK_API_KEY = 'sk-871478039084414ba753292a3a9329ae';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';

exports.main = async (event, context) => {
    try {
        const { message, userId, chatId } = event;

        // 验证用户登录状态
        if (!userId) {
            throw new Error('用户未登录');
        }

        // 构建消息对象
        const userMessage = {
            role: "user",
            content: message.content,
            images: message.images || [],
            createTime: Date.now()
        };

        // 调用Deepseek API
        const aiResponse = await callDeepseekAPI(message.content);

        // 构建AI回复消息
        const assistantMessage = {
            role: "assistant",
            content: aiResponse,
            createTime: Date.now()
        };

        // 存储到数据库
        if (chatId) {
            // 更新现有对话
            await chatCollection.doc(chatId).update({
                messages: db.command.push([userMessage, assistantMessage]),
                updateTime: Date.now()
            });
        } else {
            // 创建新对话
            await chatCollection.add({
                userId,
                messages: [userMessage, assistantMessage],
                createTime: Date.now(),
                updateTime: Date.now()
            });
        }

        return {
            code: 0,
            message: '成功',
            response: aiResponse
        };
    } catch (error) {
        console.error('AI调用失败:', error);
        return {
            code: -1,
            message: error.message || 'AI调用失败',
            response: null
        };
    }
};

// 调用Deepseek API
async function callDeepseekAPI(content) {
    const requestBody = {
        model: "deepseek-chat",
        messages: [{
            role: "user",
            content: content
        }],
        temperature: 0.7,
        max_tokens: 1000
    };

    const response = await axios.post(DEEPSEEK_API_URL, requestBody, {
        headers: {
            'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
            'Content-Type': 'application/json'
        }
    });

    return response.data.choices[0].message.content;
} 